import { addUser } from '@/apis/accessManagement/user'
import { getUserList } from '@/apis/accessManagement/user'
import { getFriendsList } from '@/apis/accessManagement/user'
import { updateUserInfo } from '@/apis/accessManagement/user'
import { deleteFriend } from '@/apis/accessManagement/user'
import { useRef,useState,useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import layout from './index.module.scss'
import uploadPhotoIcon from '@/assets/upload-photo-icon.png'
import reactSvg from '@/assets/Avatar_default.png'
import { Button, Tabs, Form, Input, Select, Switch,Flex,Modal,message,DatePicker,Radio,Spin } from 'antd'
import { Color } from 'antd/es/color-picker'
import ExcelTable from '@/components/exportExcel'
import { useLocation } from 'react-router-dom';
import type { DatePickerProps } from 'antd';
import type { RadioChangeEvent } from 'antd';
import { EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { stat } from 'fs'
import dayjs from 'dayjs';
import md5 from 'js-md5'
import {Navigate} from 'react-router-dom'

const UserDetail = () => {
    const { TextArea } = Input
    const actionRef = useRef()
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const [showPwd, setShowPwd] = useState(false)
    const [friendSwitchOn, setFriendSwitchOn] = useState(true);
    const [defaultAccount, setDefaultAccount] = useState('')
    const [defaultName, setDefaultName] = useState('')
    const [defaultUserID, setDefaultUserID] = useState('')
    const [defaultCreatTime, setDefaultCreatTime] = useState('')
    const [defaultUserStatus, setDefaultUserStatus] = useState('')
    const [defaultGender, setDefaultGender] = useState('')
    const [lastLogin, setLastLogin] = useState('')
    const [genderValue, setGenderValue] = useState(1);
    const [birthStamp, setBirthStamp] = useState(null);
    const [friendsLimit, setFriendsLimit] = useState(null);
    const location = useLocation();
    const query = new URLSearchParams(location.search);
    const state = query.get('state');
    const userID = query.get('userID');
    const [loading, setLoading] = useState(false);

    // 获取用户信息
    const getUserInfo = async (params) => {
        setLoading(true)
        try {
            const pageNum = 1
            const pageSize = 10
            const data = await getUserList({
                ...params,         
                keyword: userID,  
                normal: 1,
                pagination: {
                    pageNumber: pageNum,
                    showNumber: pageSize
                }
            });        
            if (data && data.data) {
                const { errCode, errMsg } = data;
                if (errCode === 0) {
                    const userAccount = data.data.users[0].account;
                    const userNickname = data.data.users[0].nickname;
                    const birth = dayjs(data.data.users[0].birth);
                    const userID = data.data.users[0].userID;
                    const creatTime = data.data.users[0].creatTime;
                    const lastLoginTime = data.data.users[0].lastLoginTime;
                    const gender = data.data.users[0].gender === 1?'男':'女';
                    const userStatus = data.data.users[0].userStatus === 1?'正常':'禁用';
                    setDefaultAccount(userAccount); 
                    setDefaultName(userNickname); 
                    setBirthStamp(birth); 
                    setDefaultUserID(userID); 
                    setDefaultGender(gender); 
                    setGenderValue(data.data.users[0].gender); 
                    setDefaultUserStatus(userStatus); 
                    setDefaultCreatTime(dayjs(creatTime).format('YYYY-MM-DD HH:mm:ss'))
                    setLastLogin(dayjs(lastLoginTime).format('YYYY-MM-DD HH:mm:ss'))
                    data.data.users[0].allowAddFriend === 1?setFriendSwitchOn(true):setFriendSwitchOn(false)
                    if(data.data.users[0].allowAddFriend === 1){
                        setFriendsLimit(data.data.users[0].addFriendLimit)
                    }
                }
            } 
        } catch (error) {
            console.error("获取用户信息失败:", error);
        } finally {
            setLoading(false)
        }
    };

    // ‘添加用户’前表单验证
    const handleSave = async () => {
        const userName = form.getFieldValue('name');
        const birth = form.getFieldValue('birth');
        // const birthValue = form.getFieldValue('birth');
        // const birthStamp = birthValue ? dayjs(form.getFieldValue('birth')).valueOf() : null;
        const account = form.getFieldValue('account');
        const password = form.getFieldValue('password');
        const passwordCfm = form.getFieldValue('passwordCfm');
        const limitNum = form.getFieldValue('limitNum');
        if (!userName) {
            message.error('昵称不能为空');
            return;
        }
        if (!birth) {
            message.error('出生日期不能为空');
            return;
        }
        if (state === '2' && !userID) {
            message.error('账号ID不能为空');
            return;
        }
        if (state === '1' && !password) {
            message.error('登录密码不能为空');
            return;
        }
        if (state === '1' && !passwordCfm) {
            message.error('请确认密码');
            return;
        }
        if (state === '1' && password !== passwordCfm) {
            message.error('密码输入不一致');
            return;
        }
        if (friendSwitchOn === true && !limitNum) {
            message.error('单日添加好友上限不能为空');
            return;
        }
        // try {
            const values = await form.validateFields(); // 获取表单数据并验证
            if(state === '1'){
                await subAddUser(values); 
            }else{
                await subUpdateUserInfo(values); 
            }
        // } catch (error) {
        //     console.log(error)
        // }
    };

    // 提交‘添加用户’
    const subAddUser = async (params:any) => {
        setLoading(true)
        try {
            const response = await addUser({
                // ...newParams,
                user: { 
                    nickname:form.getFieldValue('name'), 
                    gender:genderValue,
                    birth:dayjs(form.getFieldValue('birth')).valueOf(),
                    account:form.getFieldValue('account'),
                    password:md5(form.getFieldValue('password')),
                    allowAddFriend:friendSwitchOn === true?1:2,
                    addFriendLimit:friendSwitchOn === true?parseInt(form.getFieldValue('limitNum')):null,
                },
                platform:10,
                verifyCode:'666666',
                ip:'127.0.0.1'
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('用户添加成功');
                    form.resetFields(); 
                    navigate('/user/userManage/userList?current=1&pageSize=10')
                } else {
                    message.error(`添加失败: ${response?.errMsg || '未知错误'}`);
                    form.resetFields();
                }
            } else {
                message.error('响应数据格式错误');
                form.resetFields();
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    };

    // 提交‘修改用户’
    const subUpdateUserInfo = async (params:any) => {
        const { name,userID, gender,birth,nickname,...newParams } = params;
        const birthValue = form.getFieldValue('birth');
        const birthStamp = birthValue ? dayjs(birthValue).valueOf() : null;
        setLoading(true)
        try {
            const response = await updateUserInfo({
                ...newParams,
                nickname:form.getFieldValue('name'), 
                gender:genderValue,
                birth:birthStamp,
                userID:form.getFieldValue('userID'),
                allowAddFriend:friendSwitchOn === true?1:2,
                addFriendLimit:friendSwitchOn === true?parseInt(form.getFieldValue('limitNum')):null,
            });
            console.log(response)
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('用户修改成功');
                    form.resetFields(); 
                    navigate('/user/userManage/userList?current=1&pageSize=10')
                } else {
                    message.error(`修改失败: ${response?.errMsg || '未知错误'}`);
                    form.resetFields();
                }
            } else {
                message.error('响应数据格式错误');
                form.resetFields();
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    };

    // 删除好友
    const subDeleteFriend = async (record:any) => {
        setLoading(true)
        try {
            const response = await deleteFriend({
                friendUserID: record.friendUser.userID,
                ownerUserID: record.ownerUserID,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('好友删除成功');
                    actionRef.current?.reloadAndRest()
                    // window.location.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    };

    const handleFriendChange = (checked) => {
        setFriendSwitchOn(checked);
    };

    const birthChange: DatePickerProps['onChange'] = (date, dateString) => {
        if (date) {
            setBirthStamp(date.valueOf());
        } else {
            setBirthStamp(null);
        }
    };

    const genderChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setGenderValue(e.target.value);
    };

    useEffect(() => {
        if(state == '2'){
            getUserInfo(); 
        }
    }, []); 

    useEffect(() => {
        form.setFieldsValue({ account: defaultAccount });
        form.setFieldsValue({ name: defaultName });
        form.setFieldsValue({ birth: birthStamp });
        form.setFieldsValue({ userID: defaultUserID });
        form.setFieldsValue({ gender: genderValue });
        form.setFieldsValue({ allowAdd: friendSwitchOn });
        if(friendSwitchOn === true){
            form.setFieldsValue({ limitNum: friendsLimit })
        }
    }, [defaultAccount]);

    const tabsItems = [
        {
            label: '基本信息',
            key: '1',
            children: (<div style={{ maxWidth: '455px' }}>
                <Form.Item name="account" label="账号" rules={[{ required: true, message: '请输入账号' },{ max: 20, message: '用户名最多20个字符' }]}>
                    <Input allowClear placeholder='请输入账号'/>
                </Form.Item>
                <Form.Item name="name" label="昵称" rules={[{ required: true, message: '请输入昵称' },{ max: 20, message: '昵称最多20个字符' }]}>
                    <Input allowClear placeholder='请输入昵称'/>
                </Form.Item>
                <Form.Item name="birth" label="出生日期" rules={[{ required: true, message: '请输入出生日期' }]}>
                    <DatePicker onChange={birthChange} inputReadOnly/>
                </Form.Item>
                <Form.Item name="gender" label="性别">
                    <Radio.Group onChange={genderChange} defaultValue={genderValue}>
                        <Radio value={1}>男</Radio>
                        <Radio value={2}>女</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name="userID" label="账号ID" rules={[{ required: state==='2'?true:false, message: '请输入账号' }]}>
                    <Input allowClear placeholder={defaultUserID} disabled/>
                </Form.Item>
                {/* <Form.Item name="note2" label="状态" rules={[{ required: false ,message: '请选择状态'}]}>
                    <Switch defaultChecked />
                </Form.Item> */}
            </div>),
        },
        {
            label: '安全设置',
            key: '2',
            children: (
                <div>
                    {(showPwd || state == '1') ? (
                        <div>
                            <Form.Item style={{ maxWidth: '455px' }} name="password" label="登录密码" rules={[{ required: true, message: '请输入登录密码' },{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                                <Input.Password placeholder="请输入登录密码" />
                            </Form.Item>
                            <Form.Item style={{ maxWidth: '455px' }} name="passwordCfm" label="确认密码" rules={[{ required: true, message: '请再次输入密码' },{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                                <Input.Password placeholder="请再次输入密码" />
                            </Form.Item>
                        </div>
                    ) : (
                        <Flex justify="space-between">
                            <div style={{ color: '#999', marginLeft: '42px' }}>
                            密码已设置。密码至少6位字符，支持数字、字母和除空格外的特殊字符，且必须同时包含数字和大小写字母。
                            </div>
                            {state === '3' && (
                            <div style={{ color: '#165DFF', cursor: 'pointer', marginRight: '66px' }} onClick={() => { setShowPwd(true); }}>
                                修改
                            </div>
                            )}
                        </Flex>
                    )}
                </div>
            ),
        },
        {
            label: '好友权限',
            key: '3',
            children: (
                <div style={{ maxWidth: '540px' }}>
                    <Form.Item name="allowAdd" label="允许添加好友">
                        <Switch checked={friendSwitchOn} onChange={handleFriendChange}/>
                    </Form.Item>
                    {friendSwitchOn && (
                    <Form.Item name="limitNum" label="单日添加好友上限" rules={[
                        {
                            validator: (_, value) => {
                                if (value === undefined || value === '' || value >= 0) {
                                    return Promise.resolve();
                                }
                                return Promise.reject(new Error('输入值不能小于 0'));
                            },
                        },
                    ]}>
                        <Input allowClear type="number" maxLength={4} placeholder={'请输入单日添加好友上限(人)'}/>
                    </Form.Item>
                    )}

                </div>
            ),
        },
        {
            label: '关系链',
            key: '4',
            children: (
                <ExcelTable
                actionRef={actionRef}
                requestFn={ params => {
                    const { pageNum,pageSize, ...newParams } = params; 
                    const data = getFriendsList({
                        ...newParams,
                        pagination: { pageNumber: pageNum, showNumber: pageSize },
                        userID:userID
                    });
                    return data;
                }}
                rowSelection={false}
                toolBarRenderFn={() => [
                ]}
                search={false} 
                columns={[
                    {
                        title: '序号',
                        valueType: 'index',
                        hideInSearch: true
                    },
                    {
                        title: '好友ID',
                        dataIndex: 'friendUser',
                        hideInSearch: true,
                        render: (_, record) => record.friendUser?.userID || '暂无数据',
                    },
                    {
                        title: '好友昵称',
                        dataIndex: 'friendUser',
                        hideInSearch: true,
                        render: (_, record) => record.friendUser?.nickname || '暂无数据',
                    },
                    {
                        title: '添加模式',
                        dataIndex: 'addSource',
                        hideInSearch: true,
                        valueType: 'select',
                        valueEnum: {
                            null: '全部',
                            1: '管理员导入',
                            2: '申请添加'
                        }
                    },
                    // {
                    //     title: '建立好友时间',
                    //     dataIndex: '',
                    //     hideInTable: true,
                    //     valueType: 'dateRange'
                    // },
                    {
                        title: '建立好友时间',
                        dataIndex: 'createTime',
                        hideInSearch: true,
                        valueType: 'dateTime',
                        render: (_,record) => dayjs.unix(record.createTime).format('YYYY-MM-DD HH:mm:ss')
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record) => [
                            <a key="delete" onClick={() => {
                                Modal.warning({
                                    title: '提示',
                                    content: '删除该好友关系?',
                                    okText: '确定',
                                    okCancel: true,
                                    onOk() {
                                        subDeleteFriend(record)
                                    }
                                })
                            }}>删除好友关系</a>
                        ]
                    }
                ]}/>
            ),
        }
    ]

    // 根据state判断是否显示最后一个 Tab
    const visibleTabs = state == '1' ? tabsItems.slice(0, -1) : tabsItems;

    return (
        <>
        <Spin spinning={loading} fullscreen size='large'/>
        <div>
        {state === '2' && (
            <div className={layout.userInfo}>
                <div className={layout.userPhoto}>
                    <img src={reactSvg} className={layout.photo} />
                    <img src={uploadPhotoIcon} className={layout.photoIcon} />
                </div>

                <div className={layout.formView}>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>昵称:</div>
                        <div className={layout.formValue}>{defaultName}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>账号ID:</div>
                        <div className={layout.formValue}>{defaultUserID}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>注册时间:</div>
                        <div className={layout.formValue}>{defaultCreatTime}</div>
                    </div>
                </div>
                <div className={layout.formView}>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>性别:</div>
                        <div className={layout.formValue}>{defaultGender}</div>
                    </div>
                    {/* <div className={layout.formItem}>
                        <div className={layout.formLabel}>当前状态:</div>
                        <div className={layout.formValue}>{defaultUserStatus}</div>
                    </div> */}
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>最近登录时间:</div>
                        <div className={layout.formValue}>{lastLogin}</div>
                    </div>
                </div>
            </div>
        )}
            
            <div className={layout.formContent}>
                <Form form={form} className={layout.formView} labelAlign="right" labelCol={{ span: 6 }}>
                    <Tabs defaultActiveKey="1" items={visibleTabs}></Tabs>
                </Form>
            </div>
            <div className={layout.buttonView}>
                <Button type="primary" onClick={handleSave}>保存</Button>
                <Button style={{ marginLeft: 10 }} onClick={() => {
                    navigate(-1)
                }}>返回</Button>
            </div>
        </div>
        </>
    )
}

export default UserDetail